package cn.fl.mcr.controller;

import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.transform.McrCommCstAmtVOTransform;
import cn.fl.mcr.vo.McrCommCstAmtVO;
import cn.fl.mcr.vo.McrCustomerVO;
import cn.fl.spl.utils.FileUtil;
import cn.fl.system.constant.SysLogConstant;
import cn.lb.framework.poi.excel.ExcelImportUtil;
import cn.lb.framework.poi.excel.entity.ImportParams;
import cn.lionbridgecapital.loan.model.base.Pager;
import cn.lionbridgecapital.loan.model.condition.McrCommCstAmtQC;
import cn.lionbridgecapital.loan.model.constant.McrCommConstant;
import cn.lionbridgecapital.loan.model.dto.McrCommCstAmtDTO;
import cn.lionbridgecapital.loan.model.enu.IsDeleteType;
import cn.lionbridgecapital.loan.model.enu.IsSuccessType;
import cn.lionbridgecapital.loan.model.enu.IsValidType;
import cn.lionbridgecapital.loan.service.api.IMcrCommCstAmtApiService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author : yangqh521
 * @date : 2020/2/5
 * @desc : 用户提额
 */
@RestController
@RequestMapping("/mcr/mcrCstAmt")
public class McrCommCstAmtController {

    private static final Logger logger = LoggerFactory.getLogger(McrCommCstAmtController.class);

    @Autowired
    IMcrCommCstAmtApiService mcrCommCstAmtApiService;

    /**
     * 日期参数绑定
     * @param binder
     */
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder){
        CustomDateEditor customDateEditor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true);
        binder.registerCustomEditor(Date.class, customDateEditor);
    }


    /**
     * 到列表页面
     */
    @RequestMapping("/toListPage.do")
    public ModelAndView toListPage() {
        ModelAndView view = new ModelAndView("/mcr/mcrCstAmt/mcrCstAmtList");
        BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到添加页面
     */
    @RequestMapping("/toAddPage.do")
    public ModelAndView toAddPage(Long id) {
        ModelAndView view = new ModelAndView("/mcr/mcrCstAmt/mcrCstAmtAdd");
        BaseLogUtils.info(logger, "toAddPage", "跳转到新增页面, [id="+id+"]", CurrentThreadContext.getCurrentUserName());
        view.addObject("id", id);
        return view;


    }

    /**
     * 到修改页面
     *
     */
    @RequestMapping("/toModifyPage.do")
    public ModelAndView toModifyLgsPage(Long id) {
        ModelAndView view = new ModelAndView("/mcr/mcrCstAmt/mcrCstAmtModify");
        BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面, [id="+id+"]", CurrentThreadContext.getCurrentUserName());
        view.addObject("id", id);
        return view;
    }

    /**
     * 到上传页面
     */
    @RequestMapping("/toImportPage.do")
    public ModelAndView toImportPage() {
        ModelAndView view = new ModelAndView("mcr/mcrCstAmt/mcrCstAmtImport");
        BaseLogUtils.info(logger, "toImportPage", "跳转到上传页面.", CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 批量上传
     * @param filePath
     * @return
     */
    @RequestMapping("/import.do")
    public @ResponseBody DataResultVO importBatch(String filePath){
        DataResultVO resultVO = new DataResultVO(IsSuccessType.SUCCESS.getCode(), SysLogConstant.LOG_CMM_OPERATE_SUCC);

        BaseLogUtils.info(logger, "importBatch", "批量上传, filePath:" + filePath, CurrentThreadContext.getCurrentUserName());

        try {
            String rootPath = PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH);
            String realPath = rootPath + filePath;
            BaseLogUtils.info(logger, "importBatch", "批量上传, realPath:" + realPath, CurrentThreadContext.getCurrentUserName());

            ImportParams params = new ImportParams();
//            params.setTitleRows(1);//标题占用行数
            params.setHeadRows(1);//表头占用行数
            params.setNeedSave(false);//是否保存文件

            List<McrCommCstAmtDTO> list = null;
            File file = new File(realPath);
            if (file.exists()) {
                BaseLogUtils.info(logger, "importBatch", "批量上传, Excel文件存在");
                List<McrCommCstAmtVO> voList = ExcelImportUtil.importExcel(file, McrCommCstAmtVO.class, params);            BaseLogUtils.info(logger, "importBatch", "批量上传, list:" + JSON.toJSONString(list));
                BaseLogUtils.info(logger, "importBatch", "批量上传, voList:" + JSON.toJSONString(voList));
                if(CollectionUtils.isNotEmpty(voList)){
                    list = McrCommCstAmtVOTransform.toDTOList(voList);
                    for (McrCommCstAmtDTO  dto : list) {
                        dto.setCrtTm(new Date());
                        dto.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                        dto.setIsValid(IsValidType.IN_VALID.getCode()); // 初始设置为无效
                        dto.setIsDel(IsDeleteType.UN_DELETE.getCode());
                    }
                }
            }
            BaseLogUtils.info(logger, "importBatch", "批量上传, list:" + JSON.toJSONString(list));

            DataResultDTO dataResultDTO = mcrCommCstAmtApiService.uploadMcrCommCstAmtList(list);
            BaseLogUtils.info(logger, "importBatch", "批量上传异常, dataResultDTO:" + JSONObject.toJSONString(dataResultDTO));

            // 处理返回结果
            if(IsSuccessType.SUCCESS.getCode() != dataResultDTO.getSuccess()){
                resultVO.setSuccess(IsSuccessType.FAIL.getCode());
                resultVO.setInfo(dataResultDTO.getInfo());
                return resultVO;
            }

        } catch (Exception e) {
            BaseLogUtils.error(logger, "importBatch", "批量上传异常, filePath:" + filePath,
                    CurrentThreadContext.getCurrentUserName(), e);
            resultVO.setSuccess(IsSuccessType.FAIL.getCode());
            resultVO.setInfo("批量上传失败！");
            return resultVO;
        }

        BaseLogUtils.info(logger, "importBatch", "批量上传, resultVO:" + JSONObject.toJSONString(resultVO),
                CurrentThreadContext.getCurrentUserName());

        return resultVO;

    }

    /**
     * 下载模板
     */
    @RequestMapping("/download.do")
    public @ResponseBody DataResultVO download(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "download", "下载模板", CurrentThreadContext.getCurrentUserName());
        DataResultVO vo =new DataResultVO(IsSuccessType.SUCCESS.getCode(),"模板获取成功");
        String tempPath = FileUtil.getSavePath("template/mcr/McrCstAmtTemplate.xlsx");
        tempPath = tempPath.replace(
                PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH),
                PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH));
        vo.setData(tempPath);
        BaseLogUtils.info(logger, "download", " 下载模板, tempPath" + tempPath, CurrentThreadContext.getCurrentUserName());
        return vo;
    }

    /**
     * 列表数据
     * @param page
     * @param pagesize
     * @return
     */
    @RequestMapping("/initList.do")
    public @ResponseBody ListPageVO initList(@RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "10")Integer pagesize,
                        McrCommCstAmtQC qc) {
        // 查询
        Pager queryPager = new Pager();
        queryPager.setCurrentPage(page);
        queryPager.setEveryPage(pagesize);
        queryPager.setCondition(qc);
        BaseLogUtils.info(logger, "initList", "获取列表, queryPager:" + JSONObject.toJSONString(queryPager),
                CurrentThreadContext.getCurrentUserName());

        // 初始化返回数据
        Integer totalCount = 0;
        List<McrCommCstAmtVO> resultList = new ArrayList();
        try {
            Pager resultPager = mcrCommCstAmtApiService.searchMcrCommCstAmtListByPage(queryPager);
            BaseLogUtils.info(logger, "initList", "获取列表, resultPager:" + JSONObject.toJSONString(resultPager),
                    CurrentThreadContext.getCurrentUserName());
            // 处理返回数据
            if(resultPager != null && CollectionUtils.isNotEmpty(resultPager.getResultList())){
                totalCount = resultPager.getTotalCount();
                resultList = McrCommCstAmtVOTransform.toVOList((List<McrCommCstAmtDTO>)resultPager.getResultList());
            }
        } catch (Exception e) {
            BaseLogUtils.error(logger, "initList", "获取列表异常, queryPager:" + JSONObject.toJSONString(queryPager),
                    CurrentThreadContext.getCurrentUserName(), e);
        }

        // 返回数据
        ListPageVO<McrCommCstAmtVO> listPageVO = new ListPageVO<McrCommCstAmtVO>(resultList, totalCount);
        BaseLogUtils.info(logger, "initList", "获取列表, listPageVO:" + JSONObject.toJSONString(listPageVO),
                CurrentThreadContext.getCurrentUserName());
        return listPageVO;
    }

    /**
     * 单条新增新增数据
     * @return
     */
    @RequestMapping("/add.do")
    public @ResponseBody DataResultVO add(McrCommCstAmtVO vo) {

        DataResultVO resultVO = new DataResultVO(IsSuccessType.SUCCESS.getCode(), SysLogConstant.LOG_CMM_DELETE_SUCC);

        BaseLogUtils.info(logger, "add", "添加数据, vo:" + JSONObject.toJSONString(vo),
                CurrentThreadContext.getCurrentUserName());

        McrCommCstAmtDTO dto = McrCommCstAmtVOTransform.toDTO(vo);
        dto.setCrtTm(new Date());
        dto.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        dto.setIsDel(IsDeleteType.UN_DELETE.getCode());
        BaseLogUtils.info(logger, "add", "添加数据, dto:" + JSONObject.toJSONString(dto),
                CurrentThreadContext.getCurrentUserName());

        DataResultDTO dataResultDTO = null;
        try {
            List<McrCommCstAmtDTO> list = new ArrayList<>();
            list.add(dto);
            dataResultDTO = mcrCommCstAmtApiService.uploadMcrCommCstAmtList(list);
            BaseLogUtils.info(logger, "add", "添加数据, dataResultDTO:" + JSONObject.toJSONString(dataResultDTO));
        } catch (Exception e) {
            BaseLogUtils.error(logger, "add", "添加数据异常, dto:" + JSONObject.toJSONString(dto),
                    CurrentThreadContext.getCurrentUserName(), e);
            resultVO.setSuccess(IsSuccessType.FAIL.getCode());
            resultVO.setInfo("添加数据失败！");
            return resultVO;
        }

        // 处理返回结果
        if(IsSuccessType.SUCCESS.getCode() != dataResultDTO.getSuccess()){
            resultVO.setSuccess(IsSuccessType.FAIL.getCode());
            resultVO.setInfo(dataResultDTO.getInfo());
            return resultVO;
        }

        BaseLogUtils.info(logger, "add", "添加数据, resultVO:" + JSONObject.toJSONString(resultVO),
                CurrentThreadContext.getCurrentUserName());

        return resultVO;
    }


    /**
     * 主键获取
     * @return
     */
    @RequestMapping("/getById.do")
    public @ResponseBody DataResultVO getById(Long id) {

        DataResultVO resultVO = new DataResultVO(IsSuccessType.SUCCESS.getCode(), SysLogConstant.LOG_CMM_OPERATE_SUCC);

        BaseLogUtils.info(logger, "getById", "查询数据, id:" + id, CurrentThreadContext.getCurrentUserName());

        McrCommCstAmtDTO dto = null;
        try {
            McrCommCstAmtQC qc = new McrCommCstAmtQC();
            qc.setId(id);
            qc.setIsDel(IsDeleteType.UN_DELETE.getCode());
            List<McrCommCstAmtDTO> dtoList = mcrCommCstAmtApiService.searchMcrCommCstAmtList(qc);
            BaseLogUtils.info(logger, "getById", "查询数据, resultVO:" + JSONObject.toJSONString(resultVO));

            if(CollectionUtils.isNotEmpty(dtoList)){
                dto = dtoList.get(0);
            }
        } catch (Exception e) {
            BaseLogUtils.error(logger, "getById", "查询数据, id:" + id,
                    CurrentThreadContext.getCurrentUserName(), e);
            resultVO.setSuccess(IsSuccessType.FAIL.getCode());
            resultVO.setInfo("查询数据失败！");
        }
        if(dto == null){
            resultVO.setSuccess(IsSuccessType.FAIL.getCode());
            resultVO.setInfo("不存在此条数据！");
        }

        resultVO.setData(McrCommCstAmtVOTransform.toVO(dto));
        BaseLogUtils.info(logger, "getById", "查询数据, resultVO:" + JSONObject.toJSONString(resultVO),
                CurrentThreadContext.getCurrentUserName());

        return resultVO;
    }

    /**
     * 修改功能
     * @return
     */
    @RequestMapping("/modify.do")
    public @ResponseBody DataResultVO modify(McrCommCstAmtVO vo) {
        BaseLogUtils.info(logger, "modify", "修改数据, vo:" + JSONObject.toJSONString(vo));

        DataResultVO resultVO = new DataResultVO(IsSuccessType.SUCCESS.getCode(), SysLogConstant.LOG_CMM_OPERATE_SUCC);
        McrCommCstAmtDTO dto = McrCommCstAmtVOTransform.toDTO(vo);
        dto.setMdfTm(new Date());
        dto.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        DataResultDTO dataResultDTO = null;
        try {
            dataResultDTO = mcrCommCstAmtApiService.updateMcrCommCstAmt(dto);
            BaseLogUtils.info(logger, "modify", "修改数据, dataResultDTO:" + JSONObject.toJSONString(dataResultDTO));
        } catch (Exception e) {
            BaseLogUtils.error(logger, "modify", "修改数据异常, dto:" + JSONObject.toJSONString(dto),
                    CurrentThreadContext.getCurrentUserName(), e);
            resultVO.setSuccess(IsSuccessType.FAIL.getCode());
            resultVO.setInfo("添加数据失败！");
            return resultVO;
        }

        // 处理返回结果
        if(IsSuccessType.SUCCESS.getCode() != dataResultDTO.getSuccess()){
            resultVO.setSuccess(IsSuccessType.FAIL.getCode());
            resultVO.setInfo(dataResultDTO.getInfo());
            return resultVO;
        }

        BaseLogUtils.info(logger, "modify", "修改数据, resultVO:" + JSONObject.toJSONString(resultVO),
                CurrentThreadContext.getCurrentUserName());

        return resultVO;
    }

}
